package com.xinpu.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinpu.entity.*;
import com.xinpu.service.*;
import com.xinpu.util.PasswordUtils;
import com.xinpu.vo.ResponseMessage;
import com.xinpu.vo.SalesVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SalesController
 *
 * @author ayuan
 * @date 2021/4/12
 */
@RestController
@RequestMapping("/sales")
public class SalesController {


    @Resource
    private ITSalesService itSalesService;
    @Resource
    private TaskService taskService;
    @Resource
    private ITCompanyService itCompanyService;
    @Resource
    private ITUserService itUserService;

    @Resource
    private SalesService salesService;

    /**
     * 销售列表
     *
     * @param page
     * @param size
     * @param name
     * @param status
     * @param role
     * @param did
     * @return
     */
    @GetMapping("/list")
    public ResponseMessage list(
            @RequestParam("page") Integer page,
            @RequestParam("size") Integer size,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "role", required = false) Integer role,
            @RequestParam(value = "did", required = false) Integer did
    ) {
        return ResponseMessage.ok(salesService.findList(new Page(page, size), name, status, role, did, OwnService.getLoginer().getTenantId()));
    }

    /**
     * 添加销售员
     *
     * @param map
     * @return
     */
    @PostMapping("/create")
    public ResponseMessage create(@RequestBody Map<String, String> map) {
        int size = itSalesService.list().size();
        Integer num = itCompanyService.list().get(0).getNum();
        if (size >= num) {
            return ResponseMessage.error("贵公司添加的销售已达购买的套餐最大限制");
        }
        String phone = map.get("phone");
        QueryWrapper<TSales> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        TSales sales = itSalesService.getOne(wrapper);
        if (sales == null) {
            TSales tSales = new TSales();
            tSales.setAccount(map.get("account"));
            String salt = RandomUtil.randomString(6);
            String password = PasswordUtils.generatePwd(salt, map.get("password"));
            tSales.setPassword(password);
            tSales.setSalt(salt);
            tSales.setRole(Integer.parseInt(map.get("role")));
            tSales.setRemark(map.get("remark"));
            tSales.setName(map.get("name"));
            tSales.setDid(new Integer(map.get("did")));
            tSales.setPhone(phone);
            itSalesService.save(tSales);
            return ResponseMessage.ok();
        }
        return ResponseMessage.error("手机号重复");
    }

    /**
     * 修改销售员
     *
     * @param map
     * @return
     */
    @PostMapping("/update")
    public ResponseMessage update(@RequestBody Map<String, String> map) {
        Integer id = new Integer(map.get("id"));
        TSales sales = itSalesService.getById(id);
        String phone = map.get("phone");
        QueryWrapper<TSales> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        TSales sales1 = itSalesService.getOne(wrapper);
        if (sales1 != null) {
            if (!sales1.getId().equals(sales.getId())) {
                return ResponseMessage.error("手机号已存在");
            }
        }
        TSales tSales = new TSales();
        tSales.setId(id);
        tSales.setName(map.get("name"));
        tSales.setPhone(phone);
        tSales.setStatus(new Integer(map.get("status")));
        tSales.setRemark(map.get("remark"));
        tSales.setRole(Integer.parseInt(map.get("role")));
        tSales.setDid(new Integer(map.get("did")));
        itSalesService.updateById(tSales);

        return ResponseMessage.ok();
    }


    /**
     * 删除销售员
     *
     * @param map
     * @return
     */
    @PostMapping("/remove")
    public ResponseMessage remove(@RequestBody Map<String, String> map) {
        TSales tSales = itSalesService.getById(new Integer(map.get("id")));
        //将这个销售员的客户放到公海
        List<TUser> tUsers = itUserService.list(Wrappers.<TUser>lambdaQuery().eq(TUser::getPid, tSales.getId()));
        for (TUser tUser : tUsers) {
            tUser.setPid(0);
            itUserService.updateById(tUser);
        }
        return ResponseMessage.ok(itSalesService.removeById(new Integer(map.get("id"))));
    }

    /**
     * 修改密码
     *
     * @param map
     * @return
     */
    @PostMapping("/updatePassword")
    public ResponseMessage updatePassword(@RequestBody Map<String, String> map) {
        TSales tSales = new TSales();
        tSales.setId(new Integer(map.get("id")));
        String salt = RandomUtil.randomString(6);
        String password = PasswordUtils.generatePwd(salt, map.get("password"));
        tSales.setPassword(password);
        tSales.setSalt(salt);
        return ResponseMessage.ok(itSalesService.updateById(tSales));
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public ResponseMessage findById(@RequestParam("id") Integer id) {
        return ResponseMessage.ok(itSalesService.getById(id));
    }

    /**
     * 销售员任务完成情况
     *
     * @param id
     * @param start
     * @return
     */
    @GetMapping("/task")
    public ResponseMessage task(
            @RequestParam("id") Integer id,
            @RequestParam("start") String start
    ) {
        return ResponseMessage.ok(taskService.list(id, start));
    }

    /**
     * 没有分页的销售员列表
     *
     * @return
     */
    @GetMapping("salesList")
    public ResponseMessage salesList() {
        return ResponseMessage.ok(itSalesService.list());
    }

    /**
     * 销售员离职
     *
     * @param map
     * @return
     */
    @PostMapping("/leave")
    public ResponseMessage leave(@RequestBody Map<String, Integer> map) {
        TSales tSales = itSalesService.getById(map.get("id"));
        //销售员的状态改为离职
        tSales.setStatus(1);
        //销售员的租户编号改为随机数
        tSales.setTenantId(RandomUtil.randomString(40));
        //删除销售员的部门
        tSales.setDid(null);
        //删除销售员的角色
        tSales.setRole(null);
        //将这个销售员的客户放到公海
        List<TUser> tUsers = itUserService.list(Wrappers.<TUser>lambdaQuery().eq(TUser::getPid, tSales.getId()));
        for (TUser tUser : tUsers) {
            tUser.setPid(0);
            itUserService.updateById(tUser);
        }
        return ResponseMessage.ok(itSalesService.updateById(tSales));
    }
}
